package bsf.http.protocol;

import bsf.serialization.json.JsonProvider;

/**
 * Created by chejiangyi on 2017/3/31.
 */
/**
 与客户端通信协议
 */
public class ClientResult<T> {
    /** 请求回复状态码*/
    public int code;

    /** 请求是存成功*/
    public boolean getSuccess() {
        return code > 0;
    }

    public T data;

    /**
     请求返回的信息
    */
    public String msg;
    /**
     返回结果的列表数
    */
    public long total;

    /**
     服务器时间 （UTCNow - 1970-01-01）
    */
    public long servertime;

    /**
     客户端返回的文本内容
    */
    public String responsetext;

    public ClientResult<T> parse(String json, Class cls) {
        ClientResult<T> o = new ClientResult<>();
        Class resultcls = o.getClass();
        try {
            o = (ClientResult<T>) new JsonProvider().deserialize(json, resultcls);
        } catch (Exception exp) {
            try {
                //clientResult返回错误时,非标准类型的data类型返回的自动修正为默认值;
                //标准的返回错误：data应该为返回类型的默认值。
                if (json != null) {
                    ClientResult<Object> o2 = new ClientResult<>();
                    Class cls3 = o2.getClass();
                    ClientResult<Object> result = (ClientResult<Object>) new JsonProvider().deserialize(json, cls3);
                    if (result.getSuccess() == false) {
                        try {
                            result.data = cls.newInstance();
                        } catch (Exception e) {
                        }
                        o = (ClientResult<T>) new JsonProvider().deserialize(new JsonProvider().serialize(result), resultcls);
                    }
                } else
                    throw exp;
            } catch (Exception e2) {
                throw exp;
            }
        }
        o.responsetext = json;
        return o;
    }


}